package com.konsung.ksdc.manager.community;

import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ibm.mqtt.MqttClient;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.MqttMsgNotice;
import com.konsung.ksdc.bean.netbean.ContactRequestNetBean;
import com.konsung.ksdc.bean.netbean.RegisterUserNetBean;
import com.konsung.ksdc.common.database.DatabaseHelper;
import com.konsung.ksdc.common.mqtt.MqttNoticeConstant;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.config.MyApplication;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.service.MqttService;
import com.squareup.picasso.Picasso;

import java.sql.SQLException;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 创建者     kgh
 * 创建时间   2016/5/27 15:28
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述  联系人请求数据适配器
 */
public class ContactRequestListAdapter extends BaseAdapter {
    private List<ContactRequestNetBean> contactRequests;
    private ContactRequestActivity activity;

    /**
     * 构造方法
     * @param contactRequests 数据
     * @param activity 引用
     */
    public ContactRequestListAdapter(List<ContactRequestNetBean> contactRequests,
            ContactRequestActivity activity) {

        this.contactRequests = contactRequests;
        this.activity = activity;
    }

    @Override
    public int getCount() {
        return this.contactRequests.size();
    }

    @Override
    public Object getItem(int i) {
        return this.contactRequests.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup container) {
        final ContactRequestNetBean contactRequest = this.contactRequests.get(position);
        RegisterUserNetBean userToShow = contactRequest.getRequestUser();
        final String currentUserId = NetConfig.currentUser.getUserId();
        if (currentUserId.equals(contactRequest.getRequestUser().getUserId())) {
            userToShow = contactRequest.getTargetUser();
        }

        ViewHolder holder = null;
        if (convertView == null) {
            holder = new ViewHolder();
            convertView = LayoutInflater.from(MyApplication.getContext())
                    .inflate(R.layout.item_contact_request, null);
            ButterKnife.bind(holder, convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        String picPath = StringUtils.appendPicPath(userToShow.getUserPic());
        Picasso.with(container.getContext())
                .load(picPath)
                .placeholder(R.drawable.pic_talkbox_sel)
                .error(R.drawable.pic_talkbox_sel)
                .into(holder.ivContactHead);
        holder.tvNickName.setText(userToShow.getNickName());
        holder.tvRequestMark.setText(contactRequest.getMark());

        holder.btnAccept.setVisibility(View.GONE);
        holder.tvRequestState.setVisibility(View.GONE);

        if (ContactRequestNetBean.STATE_PASSED.equals(contactRequest.getState())) {
            holder.tvRequestState.setVisibility(View.VISIBLE);
            holder.tvRequestState.setText("已添加");
        } else {
            if (contactRequest.getRequestUser().getUserId().equals(currentUserId)) {
                holder.tvRequestState.setVisibility(View.VISIBLE);
                holder.tvRequestState.setText("等待验证");
            } else {
                holder.btnAccept.setVisibility(View.VISIBLE);
                holder.btnAccept.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        MqttClient client = MqttService.mqttClient;
                        if (client == null || !client.isConnected()) {
                            ToastUtils.toastContent(MyApplication.getContext(),
                                    MyApplication.getContext().getString(R.string.tip_check_net));
                            return;
                        }

                        // 执行添加好友
                        addContact(contactRequest, currentUserId);
                    }
                });
            }
        }

        return convertView;
    }

    /**
     * 添加
     * @param contactRequest 请求数据
     * @param userId 用户id
     */
    private void addContact(final ContactRequestNetBean contactRequest, String userId) {
        final String requestUserId = contactRequest.getRequestUserId();
        final String requestId = contactRequest.getId();

        RequestUtils.addContact(requestUserId, userId, requestId, new
                RequestCallback() {

                    @Override
                    public void onError(Call call, Exception e) {
                        e.printStackTrace();
                        Toast.makeText(MyApplication.mCurrentActivity,
                                activity.getString(R.string.add_contact_failed),
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        String resultCode = responseBean.getResultCode();
                        final String result = responseBean.getEntity(String.class);

                        if (Constants.REQUEST_OK.equals(resultCode)) {

                            // 重新加载请求列表
                            activity.loadContactRequests();

                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    Looper.prepare();

                                    try {
                                        activity.saveContactToDb(contactRequest
                                                .getRequestUser());
                                        activity.sendMessage(contactRequest
                                                .getRequestUser().getUserName());
                                        updateNotice(contactRequest.getRequestUserId());
                                        Toast.makeText(MyApplication
                                                        .mCurrentActivity, result,
                                                Toast.LENGTH_SHORT).show();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        Toast.makeText(MyApplication.mCurrentActivity,
                                                activity.getString(R.string
                                                        .add_contact_failed),
                                                Toast.LENGTH_SHORT).show();
                                    }

                                    Looper.loop();
                                }
                            }).start();
                        } else {
                            Toast.makeText(MyApplication.mCurrentActivity, result,
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    /**
     * 修改提醒
     * @param requestUserId id
     * @throws  SQLException 异常
     */
    private void updateNotice(String requestUserId) throws SQLException {
        RuntimeExceptionDao dao = DatabaseHelper.getHelper(activity)
                .getRuntimeExceptionDao(MqttMsgNotice.class);
        List<MqttMsgNotice> notices = dao.queryBuilder()
                .where()
                .eq("topicName", requestUserId)
                .and()
                .eq("ownerUserId", NetConfig.currentUser.getUserId())
                .query();

        if (!notices.isEmpty()) {
            MqttMsgNotice notice = notices.get(0);
            notice.setNoticeType(MqttNoticeConstant.NOTICE_TYPE_NORMAL);
            notice.setNoticeMsg(activity.getString(R.string
                    .contact_request_passed));
            notice.setIsRead("Y");

            dao.update(notice);
        }
    }

    /**
     * 内部类
     */
    static class ViewHolder {
        @Bind(R.id.iv_contact_head)
        ImageView ivContactHead;
        @Bind(R.id.tv_nick_name)
        TextView tvNickName;
        @Bind(R.id.tv_request_mark)
        TextView tvRequestMark;
        @Bind(R.id.btn_accept)
        Button btnAccept;
        @Bind(R.id.tv_request_state)
        TextView tvRequestState;
    }
}
